package dao

import (
	"gin-study/app/models"
	"gorm.io/gorm"
	"math"
)

type Scope func(db *gorm.DB) *gorm.DB

func Paginate(tx *gorm.DB, items interface{}, page int, limit int) *models.Paginator {
	var count int64
	tx.Scopes(ScopePage(page, limit)).Find(items).Count(&count)
	return &models.Paginator{
		Page:      page,
		Limit:     limit,
		Count:     count,
		TotalPage: int64(math.Ceil(float64(count) / float64(limit))),
		Items:     items,
	}
}

func ScopePage(page int, limit int) Scope {
	return func(db *gorm.DB) *gorm.DB {
		offset := (page - 1) * limit
		return db.Offset(offset).Limit(limit)
	}
}
